package net.gz01.wallet.web.controller.api.sdk;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;

import com.alibaba.fastjson.JSON;

import net.gz01.wallet.common.ZOIDGenerate;
import net.gz01.wallet.web.config.ConfigTest;

public class HttpRequestNew {
    /**
     * //向指定URL发送GET方法的请求
     *
     *@param    url
     *            //发送请求的URL
     *@param    param
     *            //请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL //所代表远程资源的响应结果
     *
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = null;

            if(param == null  || param.equals("")){
                urlNameString = url;
            }else {
                urlNameString = url + "?" + param;
            }

            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setConnectTimeout(60*1000);
            connection.setReadTimeout(60*1000);
            // System.setProperty("sun.net.client.defaultConnectTimeout", "60000");
            // System.setProperty("sun.net.client.defaultReadTimeout", "60000");
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            //connection.setRequestProperty("Accept-Encoding", "gzip,default");
//            connection.setRequestProperty("user-agent",
//                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
//            in = new BufferedReader(new InputStreamReader(
//                    connection.getInputStream()));

            //String httpEntity;
            //httpEntity = new GzipDecompressingEntity(httpEntity);
            InputStream Pin = connection.getInputStream();
            GZIPInputStream gunzip = new GZIPInputStream(Pin);
            in = new BufferedReader(new InputStreamReader(gunzip, "UTF-8"));
            String line;
            //in.
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    //static TrustManager[] xtmArray = new MytmArray[] { new MytmArray() };// 创建信任规则列表
    private final static int CONNENT_TIMEOUT = 15000;
    private final static int READ_TIMEOUT = 15000;
    static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    /**
     * 信任所有主机-对于任何证书都不做检查 Create a trust manager that does not validate
     * certificate chains， Android 采用X509的证书信息机制，Install the all-trusting trust
     * manager
     */
    private static void trustAllHosts() {
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, null, new java.security.SecureRandom());
            HttpsURLConnection
                    .setDefaultSSLSocketFactory(sc.getSocketFactory());
            // 不进行主机名确认,对所有主机
            HttpsURLConnection.setDefaultHostnameVerifier(DO_NOT_VERIFY);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String SendPosthttpsOrhttp(String httpsurl, String param){
    	String result = null;
        HttpURLConnection http = null;
        URL url;
        try {
			url = new URL(httpsurl);
			if (url.getProtocol().toLowerCase().equals("https")) {
	            trustAllHosts();
	            http = (HttpsURLConnection) url.openConnection();
	            ((HttpsURLConnection) http).setHostnameVerifier(DO_NOT_VERIFY);// 不进行主机名确认
	            http.setConnectTimeout(CONNENT_TIMEOUT);// 设置超时时间
	            http.setReadTimeout(READ_TIMEOUT);
	            if (param == null) {
	                http.setRequestMethod("GET");// 设置请求类型
	                http.setDoInput(true);
	                // http.setRequestProperty("Content-Type", "text/xml");
//	                if (AppSession.mCookieStore != null)
//	                    http.setRequestProperty("Cookie", AppSession.mCookieStore);
	            } else {
	                http.setRequestMethod("POST");// 设置请求类型为post
	                http.setDoInput(true);
	                http.setDoOutput(true);
	                http.setRequestProperty("Content-Type", "application/json; charset=utf-8");
//	                if (AppSession.mCookieStore != null
//	                        && AppSession.mCookieStore.trim().length() > 0)
//	                    http.setRequestProperty("Cookie", AppSession.mCookieStore);

//	                DataOutputStream out = new DataOutputStream(
//	                        http.getOutputStream());
//                    out.writeBytes(param);
//	                out.flush();
//	                out.close();


                    // 获取URLConnection对象对应的输出流
                    PrintWriter out = new PrintWriter(http.getOutputStream());
                    // 发送请求参数
                    out.print(param);
                    // flush输出流的缓冲
                    out.flush();
	            }

                // 获取所有响应头字段
                Map<String, List<String>> map = http.getHeaderFields();
                // 遍历所有的响应头字段
                for (String key : map.keySet()) {
                    //LogDE.v("报文头", key + "--->" + map.get(key));
                }

	            // 设置http返回状态200（ok）还是403
	            int httpsResponseCode = http.getResponseCode();
	            BufferedReader in = null;
	            if (httpsResponseCode == 200) {
	                //getCookie(http);
	                in = new BufferedReader(new InputStreamReader(
	                        http.getInputStream()));
	            } else
	                in = new BufferedReader(new InputStreamReader(
	                        http.getErrorStream()));
	            String temp = in.readLine();
	            while (temp != null) {
	                if (result != null)
	                    result += temp;
	                else
	                    result = temp;
	                temp = in.readLine();
	            }
	            in.close();
	            http.disconnect();
	            return result;
	        }
	        else{
	        	return sendPost(httpsurl, param);
	        }
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}catch(IOException  e1){
			e1.printStackTrace();
			return null;
		}
    }

    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            conn.setConnectTimeout(60*1000);
            conn.setReadTimeout(60*1000);
            // 设置通用的请求属性
            //Content-Type: application/json; charset=utf-8\r\n
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            //conn.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");
            //conn.setRequestProperty("connection", "Keep-Alive");
//            conn.setRequestProperty("user-agent",
//                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();

            // 获取所有响应头字段
            Map<String, List<String>> map = conn.getHeaderFields();
            // 遍历所有的响应头字段
//            for (String key : map.keySet()) {
//                LogDE.v("报文头", key + "--->" + map.get(key));
//            }
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
        	//LogDE.v("Post error", "发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }


    public static String sendPost(String url, String param, String ContentType) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            conn.setConnectTimeout(60*1000);
            conn.setReadTimeout(60*1000);
            // 设置通用的请求属性
            //Content-Type: application/json; charset=utf-8\r\n
            //conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            //conn.setRequestProperty("Content-Type", "text/plain;charset=UTF-8");
            conn.setRequestProperty("Content-Type", ContentType);
            //conn.setRequestProperty("connection", "Keep-Alive");
//            conn.setRequestProperty("user-agent",
//                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();

            // 获取所有响应头字段
            Map<String, List<String>> map = conn.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                //LogDE.v("报文头", key + "--->" + map.get(key));
            }
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            //LogDE.v("Post error", "发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

    private static void kdlq_route() {

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
        String reqtime = (df.format(new Date()));// new Date()为获取当前系统时间

//        String openid = this.getPara("openid");
//        String sub_mich = this.getPara("sub_mich");
//        String fee = this.getPara("menoy");
        HashMap<String, String> paraMap = new HashMap<String, String>();

        paraMap.put("version", "1.0.0");
        paraMap.put("reqtime", reqtime);
        paraMap.put("orderTime", reqtime);
        paraMap.put("rancode", WXPayUtil.generateNonceStr());
        paraMap.put("systemCode", "20010");
        paraMap.put("payTypeCode", "wxPub");
        paraMap.put("terminalType", "WEB");
        paraMap.put("merchantNo", ConfigTest.G_merchantNo);
        paraMap.put("notifyUrl", "http://www.baidu.com");
        paraMap.put("callBackUrl", "http://www.baidu.com");
        paraMap.put("outTradeNo", "AKMT" + ZOIDGenerate.nextOrderNo());
        paraMap.put("amount", "0.02");
        paraMap.put("title", "KMT");
        paraMap.put("payment", "40005");
        try {
            paraMap.put("sign", WXPayUtil.generateSignature(paraMap, ConfigTest.G_key, WXPayConstants.SignType.MD5));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("sign=" + paraMap.get("sign"));
        String param = JSON.toJSONString(paraMap);
        String httpsurl = "https://www.koudailingqian.com/merchantpay/trade/order";
        System.out.println("URL---kdlq----->:" + httpsurl);
        System.out.println("SEND---kdlq----->:" + param);
        //String res = HttpRequestNew.SendPosthttpsOrhttp(httpsurl, param);
        //System.out.println("RECV---kdlq----->:" + res);
    }


//    public static void main(String[] args){
//        new FaDadaController().kdlq_route();
//    }



    private static int i = 0;

    public static void main(String[] args) {

        kdlq_route();
        //发送 GET 请求
        //String s=HttpRequestNew.sendGet("http://14.29.111.142:8092/posm/MSP0002.tran2", "partnerid=160010&MESDAT={\"BIT00\":\"0700\",\"BIT03\":\"180010\",\"BIT04\":\"000000000001\",\"BIT11\":\"748441\",\"BIT25\":\"00\",\"BIT32\":\"001\",\"BIT34\":\"00000000000000748441\",\"BIT41\":\"90117839\",\"BIT42\":\"894440155416002\",\"BIT49\":\"156\",\"BIT59\":{\"auth_code\":\"130535594870740980\",\"randomKey\":\"748441\",\"trade_type\":\"100002\"},\"BIT64\":\"37F5966C96DB8461371E90A27B13D6C658E5F001\"}");
        //System.out.println(s);
//        for(i = 0; i < 0; i++){
//            System.out.println("第  " + i + "个线程");
//
//            new Thread(new Runnable() {
//
//                @Override
//                public void run() {
//                    int cc = i;
//                    // TODO Auto-generated method stub
//                    while(true){
//                        System.out.println("运行第  " + cc + "个线程");
//                        //发送 POST 请求
//                        String sr= HttpRequestNew.sendPost("http://192.168.1.47:7070/ServiceApi/ShopMatching", "{\"Shop_ID\":\"3634BC671D6E40ED95CEAF5EF0B3C699\"}");
//                        System.out.println(sr);
//
//                        try {
//                            Thread.sleep(2000);
//                        } catch (InterruptedException e) {
//                            // TODO Auto-generated catch block
//                            e.printStackTrace();
//                        }
//
//                        //发送 GET 请求
//                        String s= HttpRequestNew.sendGet("http://192.168.1.47:7070/ServiceApi/GetShopSeatList", "");
//                        System.out.println(s);
//
//                    }
//                }
//            }).start();
//        }


    }
}

